﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Flagwind.Data
{
	public static class CommandExtensions
	{
		public static List<T> ToList<T>(this Command command) where T : class, IEntity, new()
		{
			return DataAccess<T>.Instance.Select(command).ToList();
		}

		public static List<T> ToList<T>(this Command command, IDataProvider provider) where T : class, IEntity, new()
		{
			return DataAccess<T>.Instance.Select(command, provider).ToList();
		}

		public static IList<TResult> ToList<TResult>(this Command command, ECResultFunc<TResult> func) where TResult : class
		{
			var container = new EntityContainer(command);
			return container.ToObjectList<TResult>(func);
		}

		public static IList<TResult> ToList<TResult>(this Command command, IDataProvider provider, ECResultFunc<TResult> func) where TResult : class
		{
			var container = new EntityContainer(command, provider);
			return container.ToObjectList<TResult>(func);
		}

		public static T ToSingle<T>(this Command command) where T : class, IEntity, new()
		{
			return DataAccess<T>.Instance.Find(command);
		}

		public static T ToSingle<T>(this Command command, IDataProvider provider) where T : class, IEntity, new()
		{
			return DataAccess<T>.Instance.Find(command, provider);
		}

		public static int Execute(this Command command)
		{
			return new DataAccess().Execute(command);
		}

		public static int Execute(this Command command, IDataProvider provider)
		{
			return new DataAccess().Execute(command, provider);
		}

		public static int[] FilterEnumValues(this Type enumType, int containValue)
		{
			var values = Enum.GetValues(enumType) as int[];
			return (from enumArrA in Enumerable.Range(0, 1 << values.Length) select (from enumArrB in Enumerable.Range(0, values.Length) where (enumArrA & (1 << enumArrB)) != 0 select values[enumArrB]).Sum()).Where(x => (x & containValue) == x).Distinct().ToArray();
		}
	}
}